<?php
namespace app\common\model\shop\ozon;

use app\common\model\shop\CurrencyModel;
use app\common\model\shop\ShopsModel;
use app\common\service\shop\Ozon;
use think\admin\Model;
use think\admin\model\SystemUser;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

/**
 * OzonGoodsModel
 * ozon商品
 * @Description
 * @package app\common\model\shop\ozon
 * @author wangqinghui
 * @date 2024-11-01 09:29
 */
class OzonGoodsModel extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'shop_goods_ozon';

    // 自动写入时间戳
    protected $autoWriteTimestamp = false;

    /**
     * 日志名称
     * @var string
     */
    protected $oplogName = 'ozon商品';

    /**
     * 日志类型
     * @var string
     */
    protected $oplogType = 'ozon商品管理';

    public static function from_arr() : array
    {
        return [0 => lang('未知'), 1 => lang('数据采集'), 2 => lang('手工创建')];
    }

    /**
     * 推送状态集合
     * @Description
     * @author wangqinghui
     * @date 2024-12-14 17:13
     * @return array
     */
    public static function pushStatusArr() : array
    {
        return [0 => lang('未推送'), 1 => lang('推送处理中'), 2 => lang('推送成功'), 3 => lang('推送失败')];
    }

    public function userName(): \think\model\relation\HasOne
    {
        return $this->hasOne(SystemUser::class,'id','user_id')->bind(['create_name' => 'nickname']);
    }

    public function updateName(): \think\model\relation\HasOne
    {
        return $this->hasOne(SystemUser::class,'id','update_user_id')->bind(['update_name' => 'nickname']);
    }

    public function skuList(): \think\model\relation\HasMany
    {
        return $this->hasMany(OzonGoodsSkuModel::class, 'goods_id');
    }


     /* 获取ozon平台分类
     * @param $shop_id
     * @return array|mixed|void
     */
    public function getCategoryList($shop_id)
    {
        $tree = Cache::get('ozon_category_tree');
        if(!empty($tree)) {
            return $tree;
        }
        if(!$shop_id) {
            return [];
        }
        // 获取配置参数
        $info = ShopsModel::mq()->where(['is_deleted' => 0])->find($shop_id);
        if(!$info) {
            return [];
        }
        $client_id = $info['client_id'];
        $api_key = $info['api_key'];
        if(empty($api_key) || empty($client_id)) {
            return [];
        }
        $ozon_api = new Ozon(['client_id' => $client_id, 'api_key' => $api_key]);
        $data = $ozon_api->GetCategoryTree();
        if($data['code'] == 1) {
            $tree = self::dealCategoryTree($data['data']);
            // 缓存数据
            Cache::set('ozon_category_tree', $tree, 86400 * 3);
            return ['code' => 1, 'data' => $tree, 'msg' => ''];
        } else {
            return ['code' => 0, 'data' => [], 'msg' => $ozon_api->getErr()];
        }
    }

    /**
     * 处理分类树数据
     * @param $array
     * @return array
     */
    public function dealCategoryTree($array, $description_category_id = 0)
    {
        if (empty($array)) {
            return [];
        }
        $tree = array();
        foreach($array as $item) {
            $tree[] = [
                'id' => $item['description_category_id'] ?? $item['type_id'],
                'title' => $item['category_name'] ?? $item['type_name'],
                'description_category_id' => $description_category_id,
                'disabled' => $item['disabled'],
                'children' => self::dealCategoryTree($item['children'], $item['description_category_id'] ?? 0),
            ];
        }
        return $tree;
    }

    /**
     * 获取属性列表
     * @param $shop_id
     * @param $description_category_id
     * @param $type_id
     * @return array|void
     */
    public function getBrandByPages($shop_id, $description_category_id, $type_id)
    {
        if(!$shop_id) {
            return [];
        }
        // 获取配置参数
        $info = ShopsModel::mq()->where(['is_deleted' => 0])->find($shop_id);
        if(!$info) {
            return [];
        }
        $client_id = $info['client_id'];
        $api_key = $info['api_key'];
        if(empty($api_key) || empty($client_id)) {
            return [];
        }
        $ozon_api = new Ozon(['client_id' => $client_id, 'api_key' => $api_key]);
        $data = $ozon_api->getBrandByPages($description_category_id, $type_id);
        $data['msg'] = '';
        if($data['code'] == 0) {
            $data['msg'] = $ozon_api->getErr();
        }
        return $data;
    }

    /**
     * 获取属性值
     * @param $shop_id
     * @param $attribute_id
     * @param $description_category_id
     * @param $type_id
     * @return array
     */
    public function getAttrValue($shop_id, $attribute_id, $description_category_id, $category_id)
    {
        if(!$shop_id) {
            return [];
        }
        // 获取配置参数
        $info = ShopsModel::mq()->where(['is_deleted' => 0])->find($shop_id);
        if(!$info) {
            return [];
        }
        $client_id = $info['client_id'];
        $api_key = $info['api_key'];
        if(empty($api_key) || empty($client_id)) {
            return [];
        }
        $ozon_api = new Ozon(['client_id' => $client_id, 'api_key' => $api_key]);
        $data = $ozon_api->getAttributeByPages($attribute_id, $description_category_id, $category_id);
        $data['msg'] = '';
        if($data['code'] == 0) {
            $data['msg'] = $ozon_api->getErr();
            $data['data'] = [];
        }
        return $data;
    }

    /**
     * 构建推送商品数据
     *
     * @param  array $goods_list 商品列表
     * @param  array $ids        商品id集合
     * @param  array $shop_data  店铺配置信息
     * @return array
     */
    public function getPushGoodsData (array $goods_list,array $ids, array $shop_data) : array
    {
        // 获取sku信息
        $sku_list = OzonGoodsSkuModel::whereIn('goods_id', $ids)->select()->toArray();
        $goods_data = array_column($goods_list, null, 'id');
        // 获取店铺币种信息
        $currency_ids = array_column($shop_data, 'currency_id');
        $currency_data = CurrencyModel::mk()->where('id', 'in', $currency_ids)->column('id,abbreviation', 'id');
        // 获取商品分类
        $category_ids = array_column($goods_list, 'category_id');
        $category_data = [];
        if(!empty($category_ids)){
            $map = [
                ['type_id', 'in', $category_ids],
            ];
            $category_data = OzonGoodsCategoryModel::mk()->where($map)->column('pid', 'type_id');
        }
        // 获取商品规格
        $map = [
            ['goods_id', 'in', $ids],
            ['checked',     '=', 1],
            ['feature_id', '>=', 1]
        ];
        $sku_attr_list = OzonGoodsAttributeModel::mk()->where($map)->column('id,feature_id,value,goods_id', 'id');
        $shop_goods = [];
        $error_data = [];
        if(!empty($sku_list)){
            foreach ($sku_list as $key => $value) {
                // 商品信息
                $goods_info = !empty($goods_data[$value['goods_id']]) ? $goods_data[$value['goods_id']] : [];
                // 获取店铺信息
                $shop_id = !empty($goods_info['shop_id']) ? $goods_info['shop_id'] : 0;
                $shop_info = $shop_data[$shop_id] ?? [];
                $vat_map = self::getMapVatArr();
                $feature_list = !empty($goods_info['feature_value']) ? json_decode($goods_info['feature_value'], 1) : [];
                $category_id = !empty($goods_info['category_id']) ? $goods_info['category_id'] : 0;
                $attributes = $this->assemSkuAttrList($category_id, $feature_list, $value['attribute_ids'], $sku_attr_list, $goods_info);
                $goods_title = !empty($goods_info['title']) ? $goods_info['title'] : '';
                $sku_title = $goods_title;
                if(!empty($goods_info['push_status']) && ($goods_info['push_status'] == 1)){
                    $error_data[$value['goods_id']] = 'SPU:'.$goods_info['spu_code'].'推送处理中，请勿重复处理';
                    continue;
                }
                if(empty($category_id) || ($category_id <= 0)){
                    $error_data[$value['goods_id']] = 'SPU:'.$goods_info['spu_code'].'缺少分类信息';
                    continue;
                }
                if(empty($attributes) || empty($value['goods_nu']) || empty($sku_title) || empty($value['image']) || empty($value['price']) 
                || empty($value['weight']) || empty($value['length']) || empty($value['width']) || empty($value['height'])){
                    $error_data[$value['goods_id']] = 'SPU:'.$goods_info['spu_code'].'下sku缺少尺寸价格图片等属性标题等信息';
                    continue;
                }
                // 组装信息
                $item_info = [
                    'attributes'    => array_values($attributes),// 商品特性组
                    'barcode'       => $value['barcode'] ?? '',// 商品条码
                    //类别ID
                    'description_category_id'   => !empty($category_data[$category_id]) ? $category_data[$category_id] : 0,
                    'new_description_category_id'   => 0,// 新类别ID
                    'color_image'   => '',//营销色彩。 格式：公共云存储中图像链接的URL。 链接的图像格式为JPG
                    'complex_attributes'    => [],//具有嵌套属性的特征组
                    // 价格显示的货币。 传输值必须与个人中心设置中所设置的货币相匹配。
                    'currency_code' => !empty($currency_data[$shop_info['currency_id']]['abbreviation']) ? $currency_data[$shop_info['currency_id']]['abbreviation'] : '',
                    'depth' =>  !empty($value['length']) ? round($value['length']*10) : 0,//包装厚度
                    'dimension_unit'    =>  'mm',// 尺寸测量单位: mm — 毫米,cm — 厘米,in — 英寸
                    'height'  => !empty($value['height']) ? round($value['height']*10) : 0,//包装高度
                    'images'    => [],//图像组。 最多15件。 图像以与组中相同的顺序显示在网站上。如果不传递值 primary_image, 组中的第一个图像将是商品的主图。
                    'images360' => [],//图像组360。至70件。格式：公共云存储中图像链接的URL。 链接的图像格式为JPG。
                    'name'      =>  $sku_title,// 商品名称
                    'offer_id'  =>  $value['goods_nu'],// 卖方系统中的商品ID — 货号
                    'old_price' =>  $value['sale_price'] ?? 0,// 商品原价
                    'pdf_list'  =>  [],// PDF-文件清单。
                    'price'     => $value['price'] ?? 0,// 商品价格，包括折扣，显示在商品卡上。 如果商品没有折扣，请指定 此参数中 old_price 的值。
                    'primary_image'    => $value['image'] ?? '',// 商品主图。
                    // 商品类型的标识符
                    'type_id'   => $category_id ?? 0,
                    // 商品增值税税率:0 — 免除增值税,0.1 — 10%,0.2 — 20%。
                    'vat'       => !empty($vat_map[$goods_info['vat_type']]) ? $vat_map[$goods_info['vat_type']] : '0',
                    "weight" => !empty($value['weight']) ? round($value['weight']) : 0, // 含包装的商品重量。 限值为1000公斤或其他换算值 计量单位。
                    "weight_unit" => "g", // 测重单位：g — 克,kg — 公斤,lb — 磅。
                    "width" => !empty($value['width']) ? round($value['width']*10) : 0, // 包装宽度。
                    'sku_id'    =>  $value['id'],// skuID
                    'goods_id'   => $value['goods_id'],// 商品ID
                ];
                $shop_goods[$shop_id][] = $item_info;
            }
        }
        $assem_data = ['success' => $shop_goods, 'error' => $error_data];
        return $assem_data;
    }

    /**
     * 组装属性
     * @param integer $category_id
     * @param array $feature_list
     * @param string $sku_attr_ids
     * @param array $sku_feature_data
     * @param array $goods_data
     * @Description
     * @author wangqinghui
     * @date 2024-11-22 16:09
     * @return array
     */
    protected function assemSkuAttrList(int $category_id, array $feature_list, string $sku_attr_ids, array $sku_feature_data, array $goods_data) : array
    {
        $sku_id_arr = !empty($sku_attr_ids) ? explode(',', $sku_attr_ids) : [];
        foreach ($sku_id_arr as $key => $value) {
            $sku_attr_info = $sku_feature_data[$value] ?? [];
            $feature_id = $sku_attr_info['feature_id'] ?? 0;
            if(empty($feature_id)){
                continue;
            }
            $feature_value = $sku_attr_info['value'] ?? '';
            $feature_list[$feature_id] = $feature_value;
        }
        $attribute_list = [];
        if(!empty($feature_list)){
            $feature_ids = array_keys($feature_list);
            $map = [
                ['feature_id', 'in', $feature_ids],
                ['category_id', '=' , $category_id]
            ];
            $feature_data = OzonGoodsFeatureModel::mk()->where($map)->column('feature_id,name,attribute_complex_id,input_type', 'feature_id');
            foreach ($feature_list as $attr_id => $item) {
                $input_type = $feature_data[$attr_id]['input_type'] ?? 0;
                if($input_type == 1){
                    $feature_value_arr = !empty($item) ? explode(',', $item) : [];
                    // 获取属性值
                    $value_map = [
                        ['value_id', 'in', $feature_value_arr],
                        ['category_id', '=' , $category_id]
                    ];
                    $value_data = OzonGoodsFeatureValueModel::mk()->where($value_map)->column('value_id,value', 'value_id');
                    $values = [];
                    foreach($feature_value_arr as $f_key => $f_value){
                        $temp = [
                            'dictionary_value_id'   => $f_value,
                            'value'      => !empty($value_data[$f_value]['value']) ? $value_data[$f_value]['value'] : '',
                        ];
                        $values[] = $temp;
                    }
                }else{
                    $values = [['value' => $item]];
                }
                $attribute_info = [
                    'complex_id'    => $feature_data[$attr_id]['attribute_complex_id'] ?? 0,
                    'id'      => $attr_id ?? 0,
                    'values'     => $values
                ];
                $attribute_list[$attr_id] = $attribute_info;
            }
            // if(!isset($attribute_list[9048])){
            //     $attribute_list[9048] = [
            //         'complex_id'    => 0,
            //         'id'      => 9048,
            //         'values'     => [['value' => 'O'.$goods_data['spu_code']]]
            //     ];
            // }
            // 处理json丰富内容
            if(!isset($attribute_list[11254])){
                if(!empty($goods_data['long_desc'])){
                    $desc_json = $this->_formatDescJson($goods_data['long_desc']);
                    if(!empty($desc_json)){
                        $attribute_list[11254] = [
                            'complex_id'    => 0,
                            'id'      => 11254,
                            'values'     => [['value' => json_encode($desc_json)]]
                        ];
                    }
                }
            }
        }
        return $attribute_list;
    }

    /**
     * 获取ozon增值税映射
     * @Description
     * @author wangqinghui
     * @date 2024-11-21 19:01
     * @return array
     */
    public static function getMapVatArr(): array
    {
        return [1 => '0', 2 => '0.1', 3 => '0.2'];
    }

    /**
     * 获取vat类型列表
     * @Description
     * @author wangqinghui
     * @date 2024-11-25 14:19
     * @return array
     */
    public static function getVatList() : array
    {
        return [1 => lang('免除增值税'), 2 => '10%', 3 => '20%'];
    }

    /**
     * 推送商品到ozon
     * @param object $platform_service
     * @param array $push_data
     * @param array $shop_info
     * @Description
     * @author wangqinghui
     * @date 2025-01-16 11:15
     * @return array
     */
    public function actPushGoods(object $platform_service, array $push_data, array $shop_info): array
    {
        $ret_data = ['code' => 0, 'msg' => ''];
        if(empty($platform_service)){
            $ret_data['msg'] = '平台服务不存在';
            return $ret_data;
        }
        if(empty($push_data)){
            $ret_data['msg'] = '推送数据为空';
            return $ret_data;
        }
        $err_msg = $push_log_data = [];
        foreach (array_chunk($push_data, 100) as $key => $chunk_data) {
            $goods_nu_arr = array_column($chunk_data, 'offer_id');
            $sku_ids = array_column($chunk_data, 'sku_id');
            $goods_ids = array_column($chunk_data, 'goods_id');
            // 推送商品
            $res = $platform_service->synProduct($chunk_data);
            // 启动事务
            Db::startTrans();
            try {
                if ($res['code'] == 0) {
                    // 更新sku推送失败
                    OzonGoodsSkuModel::mk()->where('id', 'in', $sku_ids)->update(['push_status' => 3]);
                    // 更新商品推送失败
                    $map = [
                        ['id', 'in', $goods_ids],
                    ];
                    OzonGoodsModel::mk()->where($map)->update(['push_status' => 3]);
                    $goods_nu_str = !empty($goods_nu_arr) ? implode('|', $goods_nu_arr) : '';
                    $err_msg[] = $goods_nu_str.':'.$platform_service->getErr();
                    // 插入错误信息
                    $add_err = [];
                    foreach ($goods_nu_arr as $key => $goods_nu) {
                        $tmep = [
                            'type'  =>  0,
                            'offer_id'  => $goods_nu,
                            'message'   => '推送失败',
                            'description'   => $platform_service->getErr(),
                        ];
                        $add_err[] = $tmep;
                    }
                    if(!empty($add_err)){
                        OzonGoodsPushMsgModel::mk()->insertAll($add_err);
                    }
                }else{
                    $push_log_data[] = [
                        'task_id'   => $res['data']['task_id'],
                        'shop_id'   =>  $shop_info['id'] ?? 0,
                        'push_ids'  =>  implode(',', $goods_nu_arr),
                    ];
                    // 更新sku推送任务ID推送成功
                    $update_data = ['push_status' => 1, 'task_id' => $res['data']['task_id']];
                    OzonGoodsSkuModel::mk()->where('id', 'in', $sku_ids)->update($update_data);
                    $map = [
                        ['id', 'in', $goods_ids],
                    ];
                    // 全部成功更新商品SPU表成功
                    OzonGoodsModel::mk()->where($map)->update(['push_status' => 1]);
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                Log::error('[ozon商品推送失败]：'.$e->getMessage());
            }
            
        }
        if(!empty($push_log_data)){
            OzonGoodsPushLogModel::mk()->insertAll($push_log_data);
        }
        if(!empty($err_msg)){
            $ret_data['msg'] = '错误信息：'.implode('<br>', $err_msg);
            return $ret_data;
        }
        $ret_data = ['code' => 1, 'msg' => '推送成功'];
        return $ret_data;
    }

    /**
     * 生成spu
     * @Description
     * @author wangqinghui
     * @date 2024-11-28 16:28
     * @return string
     */
    public function createSPU(): string
    {
        // 获取
        $day_time = date('Y-m-d') . ' 00:00:00';
        $count = self::mk()->where('create_at', '>', $day_time)->count();
        $spu_code = date('Ymd') . str_pad($count + 1, 6, '0', STR_PAD_LEFT);
        return (string)$spu_code;
    }

    /**
     * 把详情转换为ozon的json格式
     * @param string $desc
     * @Description
     * @author wangqinghui
     * @date 2024-12-19 15:31
     * @return array
     */
    private function _formatDescJson(string $desc): array
    {
        $desc_json = [];
        if(empty($desc)){
            return $desc_json;
        }
        // Use regex to match both images and text in a single pass
        preg_match_all('/<img[^>]+src="([^"]+)"|>(.*?)<\/p>/', $desc, $matches, PREG_SET_ORDER);

        $match_ret = [];
        foreach ($matches as $key => $match) {
            // Check if it's an image match
            if (!empty($match[1])) {
                $match_ret[$key]['images'][] = $match[1];
            }
            // Check if it's a text match
            if (!empty($match[2])) {
                if(strpos($match[2], 'img') !== false){
                    preg_match_all('/<img[^>]+src="([^"]+)"/', $match[2], $img_matches);
                    $match_ret[$key]['images'] = $img_matches[1];
                }else{
                    $text_str = trim(str_replace("&nbsp;", '', htmlentities(strip_tags($match[2]))));
                    if(!empty($text_str)){
                        $match_ret[$key]['text'] = html_entity_decode($text_str);
                    }
                }
            }
        }
        if(empty($match_ret)){
            return $desc_json;
        }
        $desc_json = ['content' => [], 'version' => 0.3];
        foreach ($match_ret as $key => $item) {
            if(!empty($item['images'])){
                $widget = [
                    'widgetName'    => 'raShowcase',
                    'type'          => 'roll',
                    'blocks'        => []
                ];
                foreach ($item['images'] as $img_key => $img_value) {
                    $block = [
                        'imgLink'   => '',
                        'img'   =>  [
                            'src'   => $img_value,
                            'srcMobile'   => $img_value,
                            'alt'   => '',
                            'position'  => 'width_full',
                            'positionMobile'  => 'width_full',
                        ],
                    ];
                    $widget['blocks'][] = $block;
                }
                $desc_json['content'][] = $widget;
            }
            if(!empty($item['text'])){
                $temp_text = [
                    'size'  => 'size2',
                    'align' => 'center',
                    'color' => 'color1',
                    'content' => [$item['text']],
                ];
                $temp_title = [
                    'content'   => [],
                    'size'      => 'size2',
                    'color'     => 'color1',
                    'align'     => 'center',
                ];
                $widget = [
                    'widgetName'    => 'raTextBlock',
                    'title'         => $temp_title,
                    'theme'         => 'default',
                    'padding'       => 'type2',
                    'gapSize'       => 's',
                    'text'          => $temp_text,
                ];
                $desc_json['content'][] = $widget;
            }
        }
        return $desc_json;
    }

    
    /**
     * 获取需要推送的商品sku库存
     * @param array $goods_ids
     * @Description
     * @author wangqinghui
     * @date 2024-12-26 15:08
     * @return array
     */
    public function getStockSkuList(array $goods_ids): array
    {
        $ret = ['error' => [], 'success' => []];
        // 获取商品sku信息
        $field = 'id,goods_id,goods_nu,product_id';
        $map = [
            ['goods_id', 'in', $goods_ids]
        ];
        $sku_data = OzonGoodsSkuModel::mk()->field($field)->where($map)->select()->toArray();
        $err_data = $success_data = [];
        foreach ($sku_data as $key => $value) {
            if(empty($value['product_id'])){
                $err_data[$value['goods_nu']] = 'SKU:'.$value['goods_nu'].'未同步到ozon平台,请先推送到平台';
                continue;
            }
            $success_data[] = $value;
        }
        if(!empty($err_data)){
            $ret['error'] = $err_data;
            return $ret;
        }
        if(empty($success_data)){
            $ret['error'] = ['同步失败:没有需要同步的sku'];
            return $ret;
        }
        $goods_nu = array_column($success_data, 'goods_nu');
        // 获取商品库存
        $map = [
            ['goods_id', 'in', $goods_ids],
            ['goods_nu', 'in', $goods_nu]
        ];
        $field = 'id,shop_id,goods_id,goods_nu,warehouse_id,stock,ozon_reserved_stock,push_status';
        $stock_list = OzonGoodsSkuStockModel::mk()->field($field)->where($map)->select()->toArray();
        if(empty($stock_list)){
            $ret['error'] = ['同步失败:没有需要同步的sku库存'];
            return $ret;
        }
        $error_stock = $success_stock = $stock_id_arr = [];
        $product_id_data = array_column($success_data, 'product_id', 'goods_nu');
        foreach ($stock_list as $key => $value) {
            if(!empty($value['push_status']) && ($value['push_status'] == 1)){
                $error_stock[] = 'SKU:'.$value['goods_nu'].'库存已推送,请修改后重新推送';
                continue;
            }
            if(empty($value['shop_id'])){
                $error_stock[] = 'SKU:'.$value['goods_nu'].'店铺信息有误';
                continue;
            }
            $success_stock[$value['shop_id']][] = [
                'offer_id'      => $value['goods_nu'],
                'product_id'    => !empty($product_id_data[$value['goods_nu']]) ? $product_id_data[$value['goods_nu']] : 0,
                'warehouse_id'  => $value['warehouse_id'],
                'stock'         => (int)($value['stock'] - $value['ozon_reserved_stock']),
            ];
            $stock_id_arr[$value['warehouse_id'].$value['goods_nu']] = $value['id'];
        }
        return ['error' => $error_stock, 'success' => ['stock' => $success_stock, 'stock_id' => $stock_id_arr]];
    }

    /**
     * 推送商品库存
     * @param object $platform_service
     * @param array $stock_data
     * @param array $stock_ids
     * @Description
     * @author wangqinghui
     * @date 2024-12-26 17:54
     * @return array
     */
    public function actPushGoodsStock(object $platform_service, array $stock_data, array $stock_ids) : array
    {
        $ret_data = ['error' => [], 'success' => []];
        if(empty($platform_service)){
            $ret_data['error'] = ['平台服务不存在'];
            return $ret_data;
        }
        if(empty($stock_data) || empty($stock_ids)){
            $ret_data['error'] = ['推送库存数据为空'];
            return $ret_data;
        }
        $err_msg = [];
        foreach (array_chunk($stock_data, 100) as $chunk) {
            $push_ret = $platform_service->setProductStock($chunk);
            if($push_ret['code'] == 0){
                $goods_nu_arr = array_column($chunk, 'offer_id');
                $err_msg[] = implode('|', $goods_nu_arr).':'.$platform_service->getErr();
            }else{
                $success_ids = [];
                $success_data = !empty($push_ret['data']['result']) ? $push_ret['data']['result'] : [];
                foreach ($success_data as $key => $value) {
                    if(!empty($value['updated'])){
                        $success_ids[] = !empty($stock_ids[$value['warehouse_id'].$value['offer_id']]) ? $stock_ids[$value['warehouse_id'].$value['offer_id']] : 0;
                    }else{
                        $err_msg[$value['offer_id']] = $value['offer_id'].'库存更新失败：'.json_encode($value['errors'], JSON_UNESCAPED_UNICODE);
                        Log::error('[ozon推送商品库存失败]:'.json_encode($value, JSON_UNESCAPED_UNICODE));
                    }
                }
                if(!empty($success_ids)){
                    $map = [
                        ['id', 'in', $success_ids]
                    ];
                    OzonGoodsSkuStockModel::mk()->where($map)->update(['push_status' => 1]);
                }
            }
        }
        if(!empty($err_msg)){
            $ret_data['error'] = $err_msg;
            return $ret_data;
        }
        return $ret_data;
    }
}